// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()

  if (event.action && infoHelper[event.action]) {
    const result = await infoHelper[event.action](wxContext, event)
    return result
  }

  return {
    message: 'This action was not found',
    error: -1,
  }
}

const db = cloud.database()
const info = db.collection("solitaire_info")
const _ = db.command
const $ = _.aggregate

const infoHelper = {
  //添加接龙信息
  async add(context, params) {
    params.data._openid = context.OPENID
    params.data.date = db.serverDate()
    return await info.add({
      data: params.data
    })
  },
  //获取接龙参与列表
  async list(context, params) {
    return await info.aggregate()
      .match({
        _id: params.data._id //详情页面
      })
      .lookup({
        from: 'users',
        localField: '_openid',
        foreignField: '_openid',
        as: 'users'
      })
      .project({
        "actId": 1,
        "desc": 1,
        "imgUrls": 1,
        "name": 1,
        "tel": 1,
        "date": 1,
        users: $.arrayElemAt(['$users', 0]),
      })
      .project({
        "actId": 1,
        "desc": 1,
        "imgUrls": 1,
        "name": 1,
        "tel": 1,
        "date": 1,
        user: $.mergeObjects(['$users.userInfo', '$users']),
      })
      .project({
        "actId": 1,
        "desc": 1,
        "imgUrls": 1,
        "name": 1,
        "tel": 1,
        "date": 1,
        user: {
          avatarUrl: 1,
          nickName: 1
        },
      })
      .skip(params.data.skip)
      .limit(params.data.limit)
      .end()

  },
  //判断自己是否有参与报名
  async isSignUp(context, params) {
    return await info.where({
      _openid: context.OPENID,
      actId: params.data._id
    }).count()
  },
  //取消报名
  async cancelSignUp(context, params) {
    return await info.where({
      _openid: context.OPENID,
      actId: params.data._id
    }).remove()
  }
}